//
//  AppDelegate.swift
//  DSP
//
//  Created by tucici on 2024/5/13.
//

import UIKit
import TCCKit
import RealmSwift
let APP : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let FunctionLockPassword = "FunctionLockPassword"
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    var pwd : String = ""
    lazy var CHM : ChannelManager = ChannelManager()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        setBugly()
        RealmHelper.configRealm()
        setupCH()
        setFuncPWD()
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = DSTabBarViewController()
        self.window?.makeKeyAndVisible()
        return true
    }
    
}

extension AppDelegate{
    ///配置通道
    private func setupCH(){
        
        for ch in CHM.array{
            if ch.signArray.count >= 31{continue}
            ch.initSignArr()
        }
        
        for output in CHM.out_array{
            if output.inputArr_custom.count >= 8 {continue}
            output.initInputArr()
        }
    }
    
    ///重置全局通道数据
    func resetCH(){
        CHM = ChannelManager()
        setupCH()
        upload(CHM)
    }
    
    ///所有配置，一次性上传给蓝牙
    func upload(_ model:ChannelManager){
        let array = model.data.components(separatedBy: "|")
        for hex in array{
            if hex.count <= 0{continue}
            let data = [UInt8](hex.hexadecimal() ?? Data())
            _ = BLEData.upload(data).write(completion:nil)
        }
        NotifyTool.post(updateResetDSP)
    }
    
    ///初始化功能锁密码
    func setFuncPWD(){
        if UserDefaults.standard.value(forKey: FunctionLockPassword) == nil{
            UserDefaults.standard.setValue("123456", forKey: FunctionLockPassword)
            UserDefaults.standard.synchronize()
        }
    }
    
    ///bugly
    func setBugly(){
        let config = BuglyConfig()
#if DEBUG
        config.debugMode = true
#endif
        Bugly.start(withAppId: "a9b4ee3fe5", config:config )
    }
}
